// Copyright 2008 David Mitchell
// Released under the MIT License

using System;
using System.Runtime.InteropServices;

namespace NSDuctTape
{
	internal static class NativeString
	{
		public static string NativeStringToString(IntPtr value)
		{
			if (value == IntPtr.Zero)
				return null;

			uint length = ObjectiveCMethods.SendMessageWithUInt32Result(value, Selectors.Length);
			if (length == 0)
				return string.Empty;
			
			using (HGlobal characters = new HGlobal(sizeof(char) * (int)length))
			{
				ObjectiveCMethods.SendMessage(value, Selectors.GetCharacters, characters.ToIntPtr());
				return Marshal.PtrToStringUni(characters.ToIntPtr(), (int)length);
			}
		}

		public static IntPtr StringToNativeString(string value)
		{
			if (value == null)
				return IntPtr.Zero;

			using (HGlobal buffer = HGlobal.StringToHGlobalUni(value))
			{
				IntPtr nsString = ObjectiveCMethods.SendMessage(Classes.String, Selectors.StringWithCharactersLength, buffer.ToIntPtr(), (uint)value.Length);
				return nsString;
			}
		}
	}
}
